import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia'
import type { User, LoginRequest, LoginResponse, AuthState } from '@/types'
import { authService } from '@/services/auth'
import { userStorage } from '@/utils/storage'

export const useAuthStore = defineStore('auth', () => {
  // State
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const refreshToken = ref<string | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // Getters
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  const currentUser = computed(() => user.value)
  const authError = computed(() => error.value)

  // Actions
  const login = async (loginData: LoginRequest): Promise<boolean> => {
    try {
      isLoading.value = true
      error.value = null

      const response = await authService.login(loginData.username, loginData.password, loginData.rememberMe)
      
      // Update state
      user.value = response.user
      token.value = response.token
      refreshToken.value = response.refreshToken

      // Persist to storage
      userStorage.setUserInfo(response.user)
      userStorage.setToken(response.token, response.expiresIn * 1000)
      userStorage.setRefreshToken(response.refreshToken, response.expiresIn * 1000)

      return true
    } catch (err: any) {
      error.value = err.message || '登录过程中发生错误'
      return false
    } finally {
      isLoading.value = false
    }
  }

  const register = async (registerData: { username: string; password: string; nickname: string; email: string; phone?: string }): Promise<boolean> => {
    try {
      isLoading.value = true
      error.value = null

      await authService.register(registerData)
      
      return true
    } catch (err: any) {
      error.value = err.message || '注册过程中发生错误'
      return false
    } finally {
      isLoading.value = false
    }
  }

  const logout = async (): Promise<void> => {
    try {
      isLoading.value = true
      
      // Call logout API if token exists
      if (token.value) {
        await authService.logout()
      }
    } catch (err) {
      console.warn('Logout API call failed:', err)
    } finally {
      // Clear state regardless of API call result
      clearAuthState()
      isLoading.value = false
    }
  }

  const refreshAuthToken = async (): Promise<boolean> => {
    try {
      if (!refreshToken.value) {
        return false
      }

      const newToken = await authService.refreshToken()
      
      if (newToken) {
        token.value = newToken
        // Note: refreshToken is updated by the API service internally
        return true
      }
      
      return false
    } catch (err) {
      console.error('Token refresh failed:', err)
      return false
    }
  }

  const getCurrentUser = async (): Promise<void> => {
    try {
      if (!token.value) return

      isLoading.value = true
      const response = await authService.getCurrentUser()
      
      user.value = response
      userStorage.setUserInfo(response)
    } catch (err: any) {
      error.value = err.message || '获取用户信息失败'
    } finally {
      isLoading.value = false
    }
  }

  const clearAuthState = (): void => {
    user.value = null
    token.value = null
    refreshToken.value = null
    error.value = null
    
    // Clear storage
    userStorage.clearUserData()
  }

  const initializeAuth = (): void => {
    // Restore from storage
    const storedUser = userStorage.getUserInfo() as User | null
    const storedToken = userStorage.getToken()
    const storedRefreshToken = userStorage.getRefreshToken()

    if (storedUser && storedToken && storedRefreshToken) {
      user.value = storedUser
      token.value = storedToken
      refreshToken.value = storedRefreshToken
    }
  }

  const clearError = (): void => {
    error.value = null
  }

  const updateUser = (userData: Partial<User>): void => {
    if (user.value) {
      user.value = { ...user.value, ...userData }
      userStorage.setUserInfo(user.value)
    }
  }

  // Initialize auth state on store creation
  initializeAuth()

  return {
    // State
    user: readonly(user),
    token: readonly(token),
    refreshToken: readonly(refreshToken),
    isLoading: readonly(isLoading),
    error: readonly(error),
    
    // Getters
    isAuthenticated,
    currentUser,
    authError,
    
    // Actions
    login,
    register,
    logout,
    refreshAuthToken,
    getCurrentUser,
    clearAuthState,
    clearError,
    updateUser,
    initializeAuth
  }
})